//
//  SSModifyEmailViewController.swift
//  拾舍清洁
//
//  Created by sky.wei on 2023/2/10.
//

import UIKit

public typealias ModifyEmailResult = (_ email: String)->()

class SSModifyEmailViewController: UIViewController,UITextFieldDelegate {
    var modifyEmailResult: ModifyEmailResult?     // 闭包
    @IBOutlet weak var textField: UITextField!
    
    @IBOutlet weak var btn: UIButton!
    
    var user = SSUser()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

//        title = "设置邮箱地址"
        
        btn.titleLabel?.textColor = UIColor.black
        
        textField.borderStyle = .none
        textField.delegate = self
        textField.text = user.email
        btn.addTarget(self, action: #selector(clickAction(_:)), for: .touchUpInside)
//        btn.isEnabled = false
        
    }
    
//    func textFieldDidEndEditing(_ textField: UITextField) {
//        if (textField.text!.count > 0){
//            btn.isEnabled = true
//            btn.backgroundColor = UIColor.themeColor
//            btn.titleLabel?.textColor = UIColor.white
//        }else{
//            btn.isEnabled = false
//            btn.titleLabel?.textColor = UIColor.init(hex: "#666666")
//            btn.backgroundColor = UIColor.init(hex: "#E5E5E5")
//        }
//    }
    
    @objc func clickAction(_ btn:UIButton) {
        
        if self.textField.text?.count == 0 {
            view.makeToast("请输入邮箱")
            return
        }
        if (!Validate.email(self.textField.text ?? "").isRight) {
            view.makeToast("请输入正确邮箱格式")
            return
        }
        saveEmailRequest()
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        textField.resignFirstResponder()
    }
    
    func modifyEmailResult(_ finished: @escaping ModifyEmailResult) {
        modifyEmailResult = finished
    }

}

extension SSModifyEmailViewController {

    
    //MARK: -network
    func saveEmailRequest() {
        let text:String = textField.text!
        
        let params = [
            "email": text,
            "phoneNo": kUserPhone
                ] as! [String:AnyObject]
        
        SSProgressHUD.share.show()
        HttpConnectTools.share.request(urlString: APIUrl.share.modifyEmail_URL, parameters: params) { (result, error) in
            SSProgressHUD.share.dismiss()
            if let _ = result{
                self.view.makeToast("邮箱设置成功!")
                self.navigationController?.popViewController(animated: true)
                self.modifyEmailResult!(text)
            }else{
//                if let message = error?.userInfo["errorinfo"]{
//                    self.view.makeToast(message as? String)
//                }
            }
        }
    }
}
